package com.ponhu.ea2.goodsCenter.provider.utils;

import com.ponhu.ea2.vo.SignProp;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author luyu
 * @create 2022-01-13 15:08
 * 创纪云加密请求工具
 */
public class ReqEncryptUtil {
    private static final SecureRandom RANDOM = new SecureRandom();

    private ReqEncryptUtil() {}


    public static String buildSign(String hexBody, SignProp signProp) {
        String sign = signProp.getAppSecret() +
                "_iv" + signProp.getIv() +
                "_platform_num" + signProp.getTenantId() +
                "_token" + signProp.getToken() +
                "appKey" + signProp.getAppKey() +
                "nonce" + signProp.getNonce() +
                "reqTime" + signProp.getReqTime() +
                hexBody;
        System.out.println("before encode sign:" + sign);
        return MD5.encode(sign).toUpperCase();
    }

    public static String hexAesBody(String body, String iv, String aesKey) {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(Hex.decodeHex(aesKey.toCharArray()));
            generator.init(128, secureRandom);
            SecretKey secretKey = generator.generateKey();
            IvParameterSpec ivSpec = new IvParameterSpec(Hex.decodeHex(iv.toCharArray()));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
            byte[] bytes = cipher.doFinal(body.getBytes(StandardCharsets.UTF_8));
            return Hex.encodeHexString(bytes);
        } catch (Exception e) {
            throw new RuntimeException("hex ase error", e);
        }
    }
    public static byte[] generateIv() {
        byte[] bytes = new byte[16];
        RANDOM.nextBytes(bytes);
        return bytes;
    }

    private static class MD5 {

        private static final String[] HEX_DIGITS = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

        public static String encode(String origin) {
            String md5String = "";
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md5String = byteArrayToHexString(md.digest(origin.getBytes(StandardCharsets.UTF_8)));
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("md5 encode fail", e);
            }
            return md5String;
        }

        private static String byteArrayToHexString(byte[] b) {
            StringBuilder resultSb = new StringBuilder();

            for (byte value : b) {
                resultSb.append(byteToHexString(value));
            }
            return resultSb.toString().toUpperCase();
        }

        private static String byteToHexString(byte b) {
            int n = b;
            if (b < 0) {
                n = 256 + b;
            }
            int d1 = n / 16;
            int d2 = n % 16;
            return HEX_DIGITS[d1] + HEX_DIGITS[d2];
        }
    }
}
